<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@ page import = "java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.*" %>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>


<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Add Department</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" /> 
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	
	<style type="text/css">
		td {
			height: 50px;
		}
		
		input {
			font-size: 20px;
		}
		
		select {
			font-size: 20px;
		}
		
	   a {
	      text-decoration:none;
	   }
	</style>
</head>
<body>

<%
	// get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}

	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620");//////"&characterEncoding=tis620" Encoding Thai);
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	

	
	/* find faculty in database */
	List<Faculty> faculty = new ArrayList<Faculty>();
	
	try {			   
		ResultSet rs = connect.createStatement().executeQuery("SELECT faculty_id, faculty_name_th " 
				+ " FROM faculty " + " ORDER BY faculty_id");
		
		while(rs.next()) {
			Faculty facul = new Faculty();
			
			facul.setFacultyNameTH(rs.getString("faculty_name_th"));
			facul.setFacultyId(Integer.parseInt(rs.getString("faculty_id")));
			
			faculty.add(facul);
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
%>

	<div id="page-wrap">
			<div id="inside">
				<table border="0">
					<tr style="font-size:24px">
						<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
							<div id="header_banner-2"></div>
						</td>
						
						<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
							<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
							<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
						</td>
					</tr>
				</table>
						<div id="main-content-ac">
							
							<div class="imageFrame">เพิ่มภาควิชา</div>
						
							<br/><br/><br/><br/><br/>
						
							<center>

        						<table border="0" width=800">
        							
        							<tr style="font-size:20px">
										<form id="form1" name="form1" method="post" action="">
											<td>
												<label for="faculty"> <font size="5"><strong>คณะ</strong></font> </label>
													<label><font size="5" color="#FF0000">*</font></label>
											</td>								
											<td>
												<select name="facultyList" id="facultyList" required>
													<option value="">Select</option>
<%
													for(Faculty fac : faculty) {
%>
														<option value="<%=fac.getFacultyId()%>" id="<%=fac.getFacultyId()%>"><%=fac.getFacultyNameTH()%></option>	
<%												
													}
%>
												</select>	
											</td>  
									</tr>      
								 
									<tr style="font-size:20px">		
											<td>
												<label for="labelDepartmentTH"> <font size="5"><strong>ภาควิชา (ภาษาไทย)</strong></font> </label>
													<label><font size="5" color="#FF0000">*</font></label>
											</td>
											<td>
												<input type="text" name="departmentTH" id="departmentTH" required />  
											</td>
									</tr>
		
									<tr style="font-size:20px">
											<td>
												<label for="labelDepartmentEN"> <font size="5"><strong>ภาควิชา (ภาษาอังกฤษ)</strong></font> </label>
													<label><font size="5" color="#FF0000">*</font></label>
											</td>
											<td>
												<input type="text" name="departmentEN" id="departmentEN" required />  
												
											</td>
									</tr>
									
									<tr style="font-size:20px">
											<td>
												<label for="labelDepartmentShort"> <font size="5"><strong>ตัวย่อภาควิชา</strong></font> </label>
													<label><font size="5" color="#FF0000">*</font></label>
											</td>
											<td>
												<input type="text" name="departmentShort" id="departmentShort" required maxlength="3" />  
											</td>
									</tr>
									
									<td colspan="2">
					            		<label><font size="3" color="#FF0000">หมายเหตุ: * คือ ข้อมูลสำคัญ จำเป็นต้องกรอก</font></label>
					            	</td>

									<tr>
										<td>
												<center><input type="submit" name="save"  value="save" class="buttonStyle"/></center>
											</form>	
										</td>
										<td>
												<center><a href="admin_department.jsp"><button  class="buttonStyle">cancel</button></a></center>
											
										</td>
									</tr>
	
								</table>

						</center>
						<br><br><br><br><br>	
						
					<div style="clear: both;"></div>
						<div id="footer"></div>
			</div>		
						<div style="clear: both;"></div>		
	</div>						  

<%
		String checkButton = request.getParameter("save");

		// check save button is pressed
		if("save".equals(checkButton)) {
				
				// get value from tag
				String facultyID = request.getParameter("facultyList");
				String departmentNameTH = new String(request.getParameter("departmentTH").getBytes("ISO8859_1"),"UTF-8");
				String departmentNameEN = request.getParameter("departmentEN");
				String departmentNameShort = request.getParameter("departmentShort").toUpperCase();
				
				System.out.println("faculty : "+facultyID);////////////////////try///////////////////
				System.out.println("departmentTH : "+departmentNameTH);////////////////////try///////////////////
				System.out.println("departmentEN : "+departmentNameEN);////////////////////try///////////////////
				System.out.println("departmentShort : "+departmentNameShort);////////////////////try///////////////////
				
				// check special character
			   	Pattern regex = Pattern.compile("[$&+,:;=?@#^*<>.)(|!%]");
			   	Matcher matcherdepartmentNameTH = regex.matcher(departmentNameTH);
			   	Matcher matcherdepartmentNameEN = regex.matcher(departmentNameEN);
			 	Matcher matcherdepartmentNameShort = regex.matcher(departmentNameShort);
			   	if (matcherdepartmentNameTH.find() || matcherdepartmentNameEN.find() || matcherdepartmentNameShort.find()){
				%>
								<script language="javascript"> alert("กรุณาใส่ตัวอักษรหรือตัวเลขเท่านั้น");	</script>
				<%}else{	
				
				
				if(facultyID.equals("select") && departmentNameTH.equals("") && departmentNameEN.equals("") && departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณาเลือกคณะ ,กรอกชื่อภาควิชาภาษาไทยและภาษาอังกฤษ และชื่อย่อของภาควิชา");	</script>
<%
				}
				else if(facultyID.equals("select") && !departmentNameTH.equals("") && !departmentNameEN.equals("") && !departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณาเลือกคณะ");	</script>
<%					
				}
				else if(!facultyID.equals("select") && departmentNameTH.equals("") && !departmentNameEN.equals("") && !departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณากรอกชื่อภาควิชาภาษาไทย");	</script>
<%					
				}
				else if(!facultyID.equals("select") && !departmentNameTH.equals("") && departmentNameEN.equals("") && !departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณากรอกชื่อภาควิชาภาษาอังกฤษ");	</script>
<%					
				}
				else if(!facultyID.equals("select") && !departmentNameTH.equals("") && !departmentNameEN.equals("") && departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณากรอกตัวย่อของภาควิชา");	</script>
<%					
				}
				else if(facultyID.equals("select") && departmentNameTH.equals("") && !departmentNameEN.equals("") && !departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณาเลือกคณะ และกรอกชื่อภาควิชาภาษาไทย");	</script>
<%					
				}
				else if(facultyID.equals("select") && !departmentNameTH.equals("") && departmentNameEN.equals("") && !departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณาเลือกคณะ และกรอกชื่อภาควิชาภาษาอังกฤษ");	</script>
<%					
				}				
				else if(facultyID.equals("select") && !departmentNameTH.equals("") && !departmentNameEN.equals("") && departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณาเลือกคณะ และกรอกตัวย่อของภาควิชา");	</script>
<%					
				}				
				else if(!facultyID.equals("select") && departmentNameTH.equals("") && departmentNameEN.equals("") && !departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณากรอกชื่อภาควิชาภาษาไทยและภาษาอังกฤษ");	</script>
<%					
				}				
				else if(!facultyID.equals("select") && departmentNameTH.equals("") && !departmentNameEN.equals("") && departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณากรอกชื่อภาควิชาภาษาไทยและตัวย่อของภาควิชา");	</script>
<%					
				}				
				else if(!facultyID.equals("select") && !departmentNameTH.equals("") && departmentNameEN.equals("") && departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณากรอกชื่อภาควิชาภาษาอังกฤษและตัวย่อของภาควิชา");	</script>
<%					
				}				
				else if(facultyID.equals("select") && departmentNameTH.equals("") && departmentNameEN.equals("") && !departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณาเลือกคณะ และกรอกชื่อภาควิชาภาษาไทยและภาษาอังกฤษ");	</script>
<%					
				}				
				else if(facultyID.equals("select") && departmentNameTH.equals("") && !departmentNameEN.equals("") && departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณาเลือกคณะ และกรอกชื่อภาควิชาภาษาไทยและตัวย่อของภาควิชา");	</script>
<%					
				}				
				else if(facultyID.equals("select") && !departmentNameTH.equals("") && departmentNameEN.equals("") && departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณาเลือกคณะ และกรอกชื่อภาควิชาภาษาอังกฤษและตัวย่อของภาควิชา");	</script>
<%					
				}				
				else if(!facultyID.equals("select") && departmentNameTH.equals("") && departmentNameEN.equals("") && departmentNameShort.equals("")) {
%>
					<script language="javascript"> alert("กรุณากรอกชื่อภาควิชาภาษาไทยและภาษาอังกฤษและตัวย่อของภาควิชา");	</script>
<%					
				}		
				else {
					try {		
							// check department name exist
							ResultSet rs = connect.createStatement().executeQuery("SELECT department_name_th "
														+ " FROM department "
														+ " WHERE department_name_th='"+departmentNameTH+"'");
							
							ResultSet rs_2 = connect.createStatement().executeQuery("SELECT department_name_short "
									+ " FROM department "
									+ " WHERE department_name_short='"+departmentNameShort+"'");
							
							if(rs.next() || rs_2.next()) {
			%>
								<script language="javascript"> alert("ภาควิชานี้มีอยู่ในระบบแล้ว กรุณากรอกใหม่อีกครั้งค่ะ");	</script>
			<%								
							}
							else {
								String sql = "INSERT INTO `department`(`department_name_th`, `department_name_en`, `department_name_short`, `faculty_id`)" 
										+" VALUES ('"+ departmentNameTH +"', '"+ departmentNameEN +"', '"+ departmentNameShort +"', "+ Integer.parseInt(facultyID) + ")";
						
								connect.createStatement().executeUpdate(sql);
								
								/* Log file */
								String log = "admin add department";
								Log.writeAdminFile(log);
								Log.writeAdminFile(sql);
	%>
								<script language="javascript"> alert("บันทึกข้อมูลสำเร็จ");	</script>
								<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_department.jsp">
<%
							}
					} catch (SQLException e) {
						e.printStackTrace();
		%>
						<script language="javascript"> alert("มีข้อผิดพลาดเกิดขึ้น กรุณาลองใหม่อีกครั้งค่ะ");	</script>
		<%
					}
				}
				}
			   	connect.close();
		}
%>

</body>
</html>